/**
 * @file sleep1.c
 * @author liangwenhao (1943080020@qq.com)
 * @brief 
 * @version 0.1
 * @date 2021-07-30
 * 
 * @copyright Copyright (c) 2021
 * 
 * @authorGitee  https://gitee.com/liangwenhao
 * @authorGithub https://github.com/WHaoL
 * @authorBlogs https://blog.csdn.net/liangwenhao1108
 *  
 * @Code Description:   P269  
 *                      测试alarm()+pause()
 *                      模式sleep()的实现
 */

#include <signal.h>
#include <unistd.h>
static void sig_alrm(int signo)
{
    /* nothing to do, just return to wake up the pause */
}


/**
* 存在问题
*   1. alarm和pause非原子，如果alarm()之后 cpu后被调度出去，seconds后才回来调用pause，则可能会永久阻塞
*   2. 如果用户已经设置过了定时器，则会破坏原来的定时器，
*      sig_alrm也被内部消化掉了，外部不知这一事实
*/
unsigned int sleep1(unsigned int seconds)
{
    if (signal(SIGALRM, sig_alrm) == SIG_ERR)
        return (seconds);

    alarm(seconds);    /* start the timer */
    pause();           /* next caught signal wakes us up */
    return (alarm(0)); /* turn off timer, return unslept time */
}